package com.banfan.almond.web.annotation.AuthorityVerify;

import com.banfan.almond.base.global.*;
import com.banfan.almond.entity.entity.RoleUri;
import com.banfan.almond.utils.JsonUtils;
import com.banfan.almond.utils.RedisUtil;
import com.banfan.almond.utils.ResultUtil;
import com.banfan.almond.web.mapper.RoleUriMapper;
import com.banfan.almond.web.security.SecurityUser;
import com.banfan.almond.web.service.AdminService;
import com.banfan.almond.web.service.RoleService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@Aspect
@Component
public class AuthorityVerifyAspect {


    @Autowired
    RedisUtil redisUtil;
    @Autowired
    AdminService adminService;
    @Autowired
    RoleService roleService;
    @Autowired
    RoleUriMapper roleUriMapper;


    @Around(value = "@annotation(com.banfan.almond.web.annotation.AuthorityVerify.AuthorityVerity)")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {


        //1 获取uid；获取请求路径；
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String requestURI = request.getRequestURI();

        UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        SecurityUser principal = (SecurityUser) authentication.getPrincipal();
        Integer roleUid = principal.getRoleUid();


        String key = RedisConf.ADMIN_VISIT_MENU + SysConf.REDIS_SEGMENTATION + roleUid;
        String urisJson = redisUtil.get(key);

        List<String> uris;
        if (urisJson != null) {

            uris =(List<String>) JsonUtils.jsonToObject(urisJson, List.class);

        }else {
            QueryWrapper<RoleUri> roleUriQueryWrapper = new QueryWrapper<>();
            roleUriQueryWrapper.eq(SQLConf.ROLEUID,roleUid);
            List<RoleUri> roleUris = roleUriMapper.selectList(roleUriQueryWrapper);
            uris= roleUris.stream().map(RoleUri::getUri).collect(Collectors.toList());

            String s = JsonUtils.objectToJson(uris);
            redisUtil.setEx(key,s,1,TimeUnit.HOURS);

        }

        boolean isPermit = false;
        for (String uri : uris) {
            if (requestURI.startsWith(uri)){
                isPermit = true;
                break;
            }
        }


        if (isPermit){
            log.info("用户拥有操作权限，访问的路径: {}， roleUid ：{}", requestURI, roleUid);
            return joinPoint.proceed();

        }else {
            log.info("用户不具有操作权限，访问的路径: {}， roleUid ：{}", requestURI, roleUid);
            return ResultUtil.result(ECode.NO_OPERATION_AUTHORITY, MessageConf.RESTAPI_NO_PRIVILEGE);

        }



    }




}
